package com.kkui.liuxin.controller;

import com.kkui.liuxin.pojo.User;
import com.kkui.liuxin.service.UserService;
import com.kkui.liuxin.shiro_jwt.saltUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * @author kkui
 * descriptor:This user register controller
 * @status: 514
 */


@Slf4j
@Controller
@RequestMapping("/user")
public class Register {
    @Resource
    saltUtil saltutil;
    @Resource
    UserService server;


    @PostMapping("/register")
    @ResponseBody
    public String register (@RequestBody User user, HttpServletResponse response){
        final int NAME_MAX = 8;
        final int PASSWORD_MAX = 16;

        String rName = user.getUsername();
        String rPassWord = user.getPwd();
        if (rName.contains(" ")){
            response.setStatus(514);
            return "用户名有空格";
        }

        if ("".equals(rName) || "".equals(rPassWord)){
            response.setStatus(514);
            return "账户或密码为空";
        }
        if (rName.length()> NAME_MAX){
            response.setStatus(514);
            return "用户名过长";
        }
        if (rPassWord.length()> PASSWORD_MAX){
            response.setStatus(514);
            return "密码过长";
        }
        if (server.getUserInfoByName(rName)!=null){
            response.setStatus(514);
            return "用户名已存在";
        }


        String salt = saltutil.salt();
        Md5Hash md5Hash = new Md5Hash(rPassWord,salt,1024);

        //正常注册失败，会抛异常，这是捕捉异常进行封装，如果异常result为0
        int result =0;
        try {
            result = server.setUserRegisterInfo(rName,md5Hash.toHex(),salt);


        }catch (Exception e){
            result = 0;
        }

        if (result == 1){
            return "注册成功";
        }
        response.setStatus(514);
        return "注册失败";

    }


}
